package com.yhd.appapi.exception;

import com.yhd.controller.BaseController;
import com.yhd.enums.ResultEnum;
import com.yhd.exception.GlobalException;
import com.yhd.model.ResultDto;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler extends BaseController {

    @ExceptionHandler(value = Exception.class) //该注解声明异常处理方法
    public ResultDto exceptionHandler(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        //对于自定义异常的处理
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            ResultEnum resultEnum = ex.getResult();
            if (null == resultEnum) {
                return fail(ex.getMessage());
            }
            return fail(ex.getResult());
        } else {
            return fail(ResultEnum.SYSTEM_ERROR);
        }
    }

}
